package org.muninn.niagara.structures;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

public class BXMLBuilder
{
  private String csvFile;
  private String dir;
  private String xmlFile;
  private String eName = "element";
  private String[] tags;
  
  BXMLBuilder() {}
  
  BXMLBuilder(String f) { csvFile = f; }
  
  public void setFile(String f) { csvFile = f; }
  
  public void setElementName(String e) { eName = e; }
  
  public void convert(String e) throws Exception { eName = e; convert(); }
  
  public void convert() throws Exception
  {
    if (csvFile == null) { System.out.println("No input file specified!"); return; }

    dir = csvFile.substring(0, csvFile.lastIndexOf('\\') + 1);
    xmlFile = dir + "Export.xml";

    BufferedReader reader = new BufferedReader(new FileReader(csvFile));
    String curLine = reader.readLine();

    if (curLine == null) { System.out.println("CSV file is empty!"); return; }

    tags = curLine.split(",", -2);
    curLine = reader.readLine();

    while (curLine != null)
    {
      String[] parts = curLine.split(",", -2);
      parts = fill(parts, tags.length);
      
      DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
      DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
      Document doc = docBuilder.newDocument();
      Element rootElement = doc.createElement("root");
      doc.appendChild(rootElement);
      
      for (int i = 0; i < tags.length; i++)
      {
        if (parts[i].length() == 0 && tags[i].indexOf('*') >= 0)
        {
          System.out.println("Missing essential tag value in line " + i + "!");
          break;
        }
        
        
      }
      
      curLine = reader.readLine();
    }
  }
  
  private String[] fill(String[] arr, int len)
  {
    if (arr.length < len)
    {
      String[] temp = new String[len];
      for (int i = 0; i < len; i++)
      {
        if (i < arr.length)
          temp[i] = arr[i];
        else
          temp[i] = "";
      }
      
      return temp;
    }
    
    else
      return arr;
  }
}
